import { Component } from 'react'
import Taro from '@tarojs/taro'
import { View, Text } from '@tarojs/components'
import './index.scss'
import global from '../../global';
import { Textarea, Button, Map, Swiper, SwiperItem, Picker, Input, Image } from '@tarojs/components'
import Request from "../../api";
import Event from "../../event";
export default class Index extends Component {

  constructor(props) {
    super(props);
    this.state = {
      form: {
        type: '0',
        typeLabel: '本人',
        villageId: ""
      },
      loading: false,
      types: [
        {
          code: '0',
          label: '本人'
        },
        {
          code: '1',
          label: '访客',
        },
        {
          code: '2',
          label: '家人',
        },
        {
          code: '3',
          label: '租客'
        }
      ],
    };
  }

  componentWillMount () {

  }

  componentWillUnmount () { }

  componentDidHide () { }

  componentDidShow() {
    if (global.currentBindingVillage) {
      this.state.form.villageId = global.currentBindingVillage.villageId
    }
    this.setState({
      form: this.state.form
    })
  }

  validateForm(form) {

    let _IDRe18 = /^([1-6][1-9]|50)\d{4}(18|19|20)\d{2}((0[1-9])|10|11|12)(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/
    let _IDre15 =  /^([1-6][1-9]|50)\d{4}\d{2}((0[1-9])|10|11|12)(([0-2][1-9])|10|20|30|31)\d{3}$/

    if (!form.name) {
      Taro.showToast({
        title: '请输入真实姓名！',
        icon: "error",
        duration: 1000
      });
      return false;
    }
    if (!form.resource) {
      Taro.showToast({
        title: '请上传门禁图片',
        icon: "error",
        duration: 1000
      });
      return false;
    }
    // if (!form.remark) {
    //   Taro.showToast({
    //     title: '请输入身份证号！',
    //     icon: "error",
    //     duration: 1000
    //   })
    //   return false;
    // }
    // if (form.remark && !(_IDRe18.test(form.remark) || _IDre15.test(form.remark))) {
    //   Taro.showToast({
    //     title: '请输入正确的身份证号！',
    //     icon: "error",
    //     duration: 1000
    //   })
    //   return false;
    // }
    return true;
  }

  async submitForm() {
    if (this.state.loading || !this.validateForm(this.state.form)) {
      return;
    }
    this.state.loading = true;
    this.setState({
      loading: true
    });
    let { userId } = global.userInfo;
    try {
      const res = await Request.post('/business/face', {...this.state.form, status: 1, userId});
      if (res.data.code !== 200) {
        throw new Error();
      }
      await Taro.navigateBack();
      await Taro.showToast({
        type: 'success',
        title: '提交成功'
      })
      Event.emit('updateFaces');
    } catch (e) {
      await Taro.showToast({
        title: '提交失败请重试'
      })
    } finally {
      this.setState({
        loading: false
      })
    }
  }

  async uploadImg() {
    try {
      let res = await Taro.chooseImage({
        sourceType: ['camera','album'],
        sizeType: ['compressed']
      });
      await Taro.showLoading({
        title: '加载中...'
      });
      let uploadFileRes = await Taro.uploadFile({
        url: Request.host + '/common/upload',
        filePath: res.tempFilePaths[0],
        name: 'file',
        header: {
          'Authorization': global.token
        },
        success: async (res) => {
          console.log(res, 'sss')
          let data = JSON.parse(res.data)
          if (data.code !== 200) {
            throw new Error();
          }
          this.state.form.resource = data.fileName;
          this.setState({
            form: this.state.form
          })
          await Taro.hideLoading();
          await Taro.showToast({
            title: '上传成功！',
            type: 'success'
          })
        }
      });
    } catch (e) {
      console.log("上传文件失败")
    } finally {
      await Taro.hideLoading();
    }
  }


  render () {
    let {form, loading} = this.state;
    return (
      <View className='face_detail'>
        <View className='info_container'>
          <View className='input_item'>
            <View style={{display: 'flex'}}>
              <Text className='required'>真实姓名</Text>
              <Input value={form.name} onInput={(e) => {this.setState({form: {...form, name: e.detail.value}})}} type='text' placeholder='请输入您的真实姓名'/>
            </View>
          </View>
          <View className='input_item'>
            <View style={{display: 'flex'}}>
              <Text>身份证号</Text>
              <Input value={form.remark} onInput={(e) => {this.setState({form: {...form, remark: e.detail.value}})}} type='text' placeholder='请输入您的身份证号'/>
            </View>
          </View>
          <View className='input_item'>
            <View style={{display: 'flex'}}>
              <Text className='required'>门禁类型</Text>
              <Picker mode='selector' rangeKey={'label'} range={this.state.types} onChange={(val) => {
                console.log(val);
                this.setState({
                  form: {
                    ...this.state.form,
                    type: val.detail.value,
                    typeLabel: this.state.types[val.detail.value].label
                  },
                }, () => {
                  console.log(this.state.form)
                })
              }}>
                <Input value={form.typeLabel} type='text' disabled placeholder='请选择门禁类型'/>
              </Picker>
              <Text className='iconfont icon-arrow-right size36'/>
            </View>
          </View>
          <View className='input_item'>
            <View style={{display: 'flex'}}>
              <Text className='required'>门禁上传</Text>
              <View className='img_upload_container'>
                {
                  form.resource ?
                    <Image className='image_container' src={Request.imgHost + form.resource}/>
                    :
                    <View className='image_container' onClick={this.uploadImg.bind(this)}>
                      <Text className='iconfont icon-add size50 cars_list'/>
                    </View>
                }
              </View>
            </View>
            <Text className='tips'>请您上传图片，保证画面清晰</Text>
          </View>
          <Button loading={loading} className='submit_btn'
                  type='primary' onClick={this.submitForm.bind(this)}>提交</Button>
        </View>
      </View>
    )
  }
}
